package cn.demo.um.support.factory;

import cn.demo.um.domain.UmAttrData;
import cn.demo.um.mapper.UmAttrDataMapper;
import cn.demo.um.support.Constant;
import cn.demo.um.support.handler.MatcherHandlerWrapper;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
public class LocalCacheSearchAttrIndexFactory implements ISearchAttrIndexFactory {

    @Resource
    private UmAttrDataMapper umAttrDataMapper;
    @Autowired
    private MatcherHandlerFactory matcherHandlerFactory;
    private Map<String, Map<String, Object>> sexAttrIndexMap;

    @PostConstruct
    public void init() {
        resetIndexMap();
    }

    /**
     * 重新构建倒排索引
     */
    private void resetIndexMap(String sex) {
        List<UmAttrData> manAttrs = umAttrDataMapper.allSearchAttrBySex(sex);
        //根据属性编码分组
        Map<String, List<UmAttrData>> searchAttrs = manAttrs.stream().collect(Collectors.groupingBy(UmAttrData::getAttrCode));
        Map<String, MatcherHandlerWrapper> handlerWrapperMap = matcherHandlerFactory.getHandlerMap();
        Map<String, Object> attrIndexMap = sexAttrIndexMap.get(sex);
        //遍历属性
        searchAttrs.forEach((k, v) -> {
            MatcherHandlerWrapper matcherHandlerWrapper = handlerWrapperMap.get(k);
            Object invertedIndex = matcherHandlerWrapper.buildInvertedIndex(v);
            if (invertedIndex != null) {
                attrIndexMap.put(k, invertedIndex);
            }
        });
    }

    @Override
    public synchronized void resetIndexMap() {
        sexAttrIndexMap = new HashMap<>();
        sexAttrIndexMap.put(Constant.MAN, new HashMap<>());
        sexAttrIndexMap.put(Constant.WOMAN, new HashMap<>());
        resetIndexMap(Constant.WOMAN);
        resetIndexMap(Constant.MAN);
    }

    @Override
    public Object getIndexStructure(String attrCode, String sex) {
        if (sexAttrIndexMap == null) {
            synchronized (this) {
                if (sexAttrIndexMap == null) {
                    resetIndexMap();
                }
            }
        }
        return sexAttrIndexMap.get(sex).get(attrCode);
    }

    /*不是就别调*/
    @Override
    public List<String> getIndexs(String attrCode, String attrValue, String sex) {
        Map<String, List<String>> indexMap = (Map<String, List<String>>) getIndexStructure(attrCode,sex);
        if (indexMap == null) {
            return null;
        }
        return indexMap.get(attrValue);
    }
}
